<template>
  <div class="app-container">
    <!-- 1. 查询区：保留原有下拉框（不修改） -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企业名称" prop="lisComId">
        <el-select v-model="queryParams.lisComId" filterable placeholder="请选择企业名称" clearable size="small">
          <el-option
            v-for="dict in companiesName"
            :key="dict.comId"
            :label="dict.comName"
            :value="dict.comId"
            @keyup.enter.native="handleQuery"/>
        </el-select>
      </el-form-item>
      <el-form-item label="贷款编号" prop="lisLoaId">
        <el-select v-model="queryParams.lisLoaId" filterable placeholder="请选择贷款编号" clearable size="small">
          <el-option
            v-for="dict in loansNoOptions"
            :key="dict.loaId"
            :label="dict.loaNo"
            :value="dict.loaId"
            @keyup.enter.native="handleQuery"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 2. 功能按钮区：无修改 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:materials:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:materials:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:materials:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:materials:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 3. 表格区：无修改（仅展示数据） -->
    <el-table v-loading="loading" :data="materialsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="lisId" />
      <el-table-column label="企业名称" align="center" prop="comName" />
      <el-table-column label="近六个月流水" align="center" prop="lisSixRunWater" >
        <template slot-scope="scope">
          <el-popover placement="top-start" trigger="click">
            <a :href="'/dev-api'+scope.row.lisSixRunWater" target="_blank" title="查看最大化图片">
              <img :src="'/dev-api'+scope.row.lisSixRunWater" style="width: 300px;height: 300px">
            </a>
            <img slot="reference" style="width: 80px; border: none; cursor:pointer;" :src="'/dev-api'+scope.row.lisSixRunWater">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="企业营业执照" align="center" prop="lisWork" >
        <template slot-scope="scope">
          <el-popover placement="top-start" trigger="click">
            <a :href="'/dev-api'+scope.row.lisWork" target="_blank" title="查看最大化图片">
              <img :src="'/dev-api'+scope.row.lisWork">
            </a>
            <img slot="reference" style="width: 80px; border: none; cursor:pointer;" :src="'/dev-api'+scope.row.lisWork">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="征信报告" align="center" prop="lisReport" >
        <template slot-scope="scope">
          <el-popover placement="top-start" trigger="click">
            <a :href="'/dev-api'+scope.row.lisReport" target="_blank" title="查看最大化图片">
              <img :src="'/dev-api'+scope.row.lisReport">
            </a>
            <img slot="reference" style="width: 80px; border: none; cursor:pointer;" :src="'/dev-api'+scope.row.lisReport">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="抵押物" align="center" prop="lisPawn" >
        <template width="80" slot-scope="scope">
          <el-popover placement="top-start" trigger="click">
            <a :href="'/dev-api'+scope.row.lisPawn" target="_blank" title="查看最大化图片">
              <img :src="'/dev-api'+scope.row.lisPawn" style="width: 500px">
            </a>
            <img slot="reference" style="width: 80px; border: none; cursor:pointer;" :src="'/dev-api'+scope.row.lisPawn">
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <!-- 4. 分页区：无修改 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 5. 新增/修改弹窗：核心修改区（下拉框→输入框） -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 企业名称：下拉框→下拉框，绑定lisComId（原comName） -->
        <el-form-item label="企业名称" prop="lisComId">
          <el-select
            v-model="form.lisComId"
            filterable
            placeholder="请选择企业名称"
            size="small"
            clearable
          >
            <el-option
              v-for="dict in companiesName"
              :key="dict.comId"
              :label="dict.comName"
              :value="dict.comId"
            />
          </el-select>
        </el-form-item>
        <!-- 贷款编号：下拉框→输入框，绑定loaNo（原lisLoaId） -->
        <el-form-item label="贷款编号" prop="loaNo">
          <el-input
            v-model="form.loaNo"
            placeholder="请输入贷款编号"
            size="small"
            clearable
          />
        </el-form-item>
        <!-- 以下图片上传项：无修改 -->
        <el-form-item label="近六个月流水" prop="lisSixRunWater">
          <imageUpload v-model="form.lisSixRunWater"/>
        </el-form-item>
        <el-form-item label="企业营业执照" prop="lisWork">
          <imageUpload v-model="form.lisWork"/>
        </el-form-item>
        <el-form-item label="征信报告" prop="lisReport">
          <imageUpload v-model="form.lisReport"/>
        </el-form-item>
        <el-form-item label="抵押物" prop="lisPawn">
          <imageUpload v-model="form.lisPawn"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterials, getMaterials, delMaterials, addMaterials, updateMaterials, exportMaterials } from "@/api/system/materials";

export default {
  name: "Materials",
  data() {
    return {
      loading: true,
      exportLoading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      materialsList: [],
      companiesName: [], // 查询区下拉数据：保留（不影响查询）
      loansNoOptions: [], // 查询区下拉数据：保留（不影响查询）
      title: "",
      open: false,
      // 查询参数：仍用lisComId/lisLoaId（和后端查询接口保持一致）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lisComId: null,
        lisLoaId: null,
      },
      // 表单参数：核心修改→新增lisComId/loaNo，移除comName
      form: {
        lisId: null,
        lisComId: null, // 下拉选择的企业ID
        loaNo: null,  // 手动输入的贷款编号
        lisSixRunWater: null,
        lisWork: null,
        lisReport: null,
        lisPawn: null,
        lisDel: null
      },
      // 校验规则：核心修改→校验lisComId/loaNo（原comName/lisLoaId）
      rules: {
        lisComId: [{ required: true, message: "企业名称不能为空", trigger: "blur" }],
        loaNo: [{ required: true, message: "贷款编号不能为空", trigger: "blur" }],
        lisSixRunWater: [{ required: true, message: "近六个月流水不能为空", trigger: "blur" }],
        lisWork: [{ required: true, message: "企业营业执照不能为空", trigger: "blur" }],
        lisReport: [{ required: true, message: "征信报告不能为空", trigger: "blur" }],
        lisPawn: [{ required: true, message: "抵押物不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询材料列表：无修改（仅用于查询区下拉数据） */
    getList() {
      this.loading = true;
      listMaterials(this.queryParams)
        .then(response => {
          this.materialsList = response.rows || [];
          this.total = response.total || 0;

          // 提取查询区下拉数据（不影响新增/修改功能）
          const companySet = new Set();
          this.materialsList.forEach(item => {
            if (item.lisComId && item.comName) {
              companySet.add(JSON.stringify({ comId: item.lisComId, comName: item.comName }));
            }
          });
          this.companiesName = Array.from(companySet).map(item => JSON.parse(item));

          const loanSet = new Set();
          this.materialsList.forEach(item => {
            if (item.lisLoaId && item.loaNo) {
              loanSet.add(JSON.stringify({ loaId: item.lisLoaId, loaNo: item.loaNo }));
            }
          });
          this.loansNoOptions = Array.from(loanSet).map(item => JSON.parse(item));

          this.loading = false;
        })
        .catch(error => {
          this.$message.error("获取材料列表失败：" + (error.msg || error.message));
          this.loading = false;
        });
    },

    // 取消按钮：无修改
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置：核心修改→重置lisComId/loaNo（原comName/lisLoaId）
    reset() {
      this.form = {
        lisId: null,
        lisComId: null, // 重置企业名称下拉框
        loaNo: null,  // 重置贷款编号输入框
        lisSixRunWater: null,
        lisWork: null,
        lisReport: null,
        lisPawn: null,
        lisDel: null
      };
      this.resetForm("form");
    },

    /** 搜索/重置查询：无修改（查询区仍用下拉） */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中：无修改
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lisId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮：无修改（打开弹窗时已重置输入框） */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加材料";
    },

    /** 修改按钮：核心修改→回显lisComId/loaNo（原comName/lisLoaId） */
    handleUpdate(row) {
      this.reset();
      const lisId = row.lisId || this.ids;
      getMaterials(lisId)
        .then(response => {
          const data = response.data;
          this.form = {
            lisId: data.lisId,
            lisComId: data.lisComId, // 回显企业ID（从详情接口获取）
            loaNo: data.loaNo,    // 回显贷款编号（从详情接口获取）
            lisSixRunWater: data.lisSixRunWater,
            lisWork: data.lisWork,
            lisReport: data.lisReport,
            lisPawn: data.lisPawn,
            lisDel: data.lisDel
          };
          this.open = true;
          this.title = "修改材料";
        })
        .catch(error => {
          this.$message.error("获取材料详情失败：" + (error.msg || error.message));
        });
    },

    /** 提交按钮：无修改（但需确保后端接口接收lisComId/loaNo参数） */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 日志1：打印校验通过后的完整表单数据（确认lisComId/loaNo是否有值）
          console.log("提交前的表单数据：", this.form);
          // 日志2：确认当前调用的是新增还是修改接口
          console.log("当前操作：", this.form.lisId != null ? "修改（有lisId）" : "新增（无lisId）");

          const request = this.form.lisId != null ? updateMaterials : addMaterials;
          // 日志3：打印接口请求的参数（确认传给接口的参数是否包含lisComId/loaNo）
          console.log("传给后端的参数：", this.form);

          request(this.form)
            .then(() => {
              this.msgSuccess(this.form.lisId != null ? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
            })
            .catch(error => {
              this.$message.error((this.form.lisId != null ? "修改" : "新增") + "失败：" + (error.msg || error.message));
            });
        } else {
          // 日志4：校验失败时提示（避免用户没填就提交）
          console.log("表单校验失败！请检查必填项");
          this.$message.warning("请填写所有必填项（企业名称、贷款编号等）");
        }
      });
    },

    /** 删除/导出按钮：无修改 */
    handleDelete(row) {
      const lisIds = row.lisId || this.ids;
      this.$confirm('是否确认删除材料编号为"' + lisIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => delMaterials(lisIds))
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有材料数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.exportLoading = true;
          return exportMaterials(queryParams);
        })
        .then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {
          this.exportLoading = false;
        });
    }
  }
};
</script>